package com.java.base.exercise.current.selfcache;

import com.java.base.exercise.current.selfcache.imooccache2.ExceptionFuncation;
import com.java.base.exercise.current.selfcache.imooccache2.ImoocCache3;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

import static sun.misc.PostVMInitHook.run;

/**
 * @Author RenPu
 * @Date 2021/9/21 10:09
 * @Version 1.0
 * @Description: 压测自定义缓存框架编写
 **/
public class PressureMeasurementCache {


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        ImoocCache3<String, Integer> imoocCache3 = new ImoocCache3<>(new ExceptionFuncation());

        CountDownLatch countDownLatch = new CountDownLatch(1);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            executorService.submit(() -> {
                Integer result = null;
                try {
                    System.out.println(Thread.currentThread().getName() + "开始等待！！！！");
                    countDownLatch.await();

                    //使用ThreadLocal，每个线程都有自己的放行时间，来验证是否属于同一时间的并发
                    SimpleDateFormat simpleDateFormat = ThreadSafeFormater.threadLocal.get();
                    String format = simpleDateFormat.format(new Date());
                    System.out.println(Thread.currentThread().getName() + "      " + format + "被放行！！！！！");


                    System.out.println(Thread.currentThread().getName() + "被放行！！！！");

                    result = imoocCache3.compter("666");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                System.out.println(result);
            });

        }
        Thread.sleep(5000);
        countDownLatch.countDown();
        executorService.shutdown();
//
//        //如果线程池没有执行终止，就会进入while循环
//        while (!executorService.isTerminated()){
//
//        }
//        System.out.println("总耗时为："+(System.currentTimeMillis()-start));

    }


    static class ThreadSafeFormater {

        //创建ThreadLocal对象
        public static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() {


            /**
             * 每个线程，只会调用本方法一次，用于初始化
             * @return
             */
            @Override
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }


            /**
             * 首次调用本方法，会调用initialValue方法，后面的调用会返回第一次创建的值
             * @return
             */
            @Override
            public SimpleDateFormat get() {
                return super.get();
            }
        };


    }

}
